package dao;

import entity.IEntity;
import entity.Materia;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import vo.IValueObject;
import vo.MateriaVO;

/**
 *
 * @author Alexander
 */
public class MateriaDAO implements IDAO{

    @Override
    public void persist(IEntity entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public IValueObject find(Object id, EntityManager em) {
        return em.find(Materia.class, (int)id).toVO();
    }

    @Override
    public void update(IEntity entity, EntityManager em) {
        em.merge(entity);
    }

    @Override
    public void delete(Object id, EntityManager em) {
         Materia materia = em.getReference(Materia.class, (int) id);
        em.remove(materia);
    }
    
    public List<MateriaVO> search(Object guess, boolean byCode, EntityManager em){
        List<Materia> materias = new ArrayList<>();
        Query q;
        if (byCode){
            q = em.createQuery("SELECT m FROM Materia m "
                    + "WHERE m.codigo LIKE :codigo").setParameter("codigo", "%"+guess.toString()+"%");
        } else{
            q = em.createQuery("SELECT m FROM Materia m "
                    + "WHERE m.nombre LIKE :nombre").setParameter("nombre", "%"+guess+"%");
        }
        try{
            materias = q.getResultList();
        } catch (Exception e){
            System.out.println(e.getMessage());
        }
        List<MateriaVO> materiasVo = new ArrayList<>();
        for(Materia m : materias){
            materiasVo.add(m.toVO());
        }
        return materiasVo;
    }

    @Override
    public List<IValueObject> getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Materia.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    }
}
